'''
Created on Sep 24, 2014

@author: Siyuan Qi
'''

import numpy as np

smallNumber = 1e-30

def calIntersection(cubA, cubB):
	x11 = cubA[0, 0] if cubA[0, 0]<cubA[0, 1] else cubA[0, 1]
	x12 = cubA[0, 1] if cubA[0, 0]<cubA[0, 1] else cubA[0, 0]
	y11 = cubA[1, 0] if cubA[1, 0]<cubA[1, 1] else cubA[1, 1]
	y12 = cubA[1, 1] if cubA[1, 0]<cubA[1, 1] else cubA[1, 0]
	z11 = cubA[2, 0] if cubA[2, 0]<cubA[2, 1] else cubA[2, 1]
	z12 = cubA[2, 1] if cubA[2, 0]<cubA[2, 1] else cubA[2, 0]
	
	x21 = cubB[0, 0] if cubB[0, 0]<cubB[0, 1] else cubB[0, 1]
	x22 = cubB[0, 1] if cubB[0, 0]<cubB[0, 1] else cubB[0, 0]
	y21 = cubB[1, 0] if cubB[1, 0]<cubB[1, 1] else cubB[1, 1]
	y22 = cubB[1, 1] if cubB[1, 0]<cubB[1, 1] else cubB[1, 0]
	z21 = cubB[2, 0] if cubB[2, 0]<cubB[2, 1] else cubB[2, 1]
	z22 = cubB[2, 1] if cubB[2, 0]<cubB[2, 1] else cubB[2, 0]

	xOverlap = max(0, min(x12,x22) - max(x11,x21))
	yOverlap = max(0, min(y12,y22) - max(y11,y21))
	zOverlap = max(0, min(z12,z22) - max(z11,z21))
	return xOverlap*yOverlap*zOverlap

def calCollisionVolume(entities):
	def cameraInRoom(room):
		for i in range(3):
			if room[i][0]*room[i][1] > 0:
				return False
		return True
	
	def calVol(cub):
		return abs((cub[0, 0] - cub[0, 1])*(cub[1, 0] - cub[1, 1])*(cub[2, 0] - cub[2, 1]))
		
	def getCub(entity):
		return np.array([[entity[0], entity[4]], [entity[1], entity[5]], [entity[8], entity[9]]])
	
	vol = 0
	
	room = getCub(entities[0])
# 	if not cameraInRoom(room):
# 		vol += 100
	
	objs = []
	for entity in entities[1:]:
		if entity[10] == 1:
			objs.append(getCub(entity))
	
	for obj in objs:
		vol = vol + (calVol(obj) - calIntersection(room, obj))
	
	for i in range(len(objs)):
		for j in range(i+1, len(objs)):
				vol += calIntersection(objs[i], objs[i])
	
	return vol